__all__ = ['Db']
class Db:

    def __init__(self, *, storage_host, storage_port, storage_user, storage_pass, storage_base, **etc):

        import postgresql.exceptions
        import postgresql.driver.dbapi20 as db
        self.UniqueError = postgresql.exceptions.UniqueError
        self.con = db.connect(
            host     = storage_host,
            port     = storage_port,
            user     = storage_user,
            password = storage_pass,
            database = storage_base,
        )

        self.con.autocommit = True
        self.transaction_level = 0

        self.cur = self.con.cursor()
        self.cur.execute("set client_min_messages = 'WARNING'")

    def start(self):
        if (self.transaction_level != 0):
            raise Error('Cannot start transaction, while another transaction is working (nested transaction are not supported yet).')

        if self.transaction_level == 0:
            self.con.autocommit = False
        self.transaction_level += 1

    def commit(self):
        if (self.transaction_level == 0):
            raise Error('Cannot commit transaction, which was not started.')

        self.transaction_level -= 1
        if (self.transaction_level == 0):
            self.con.commit()
            self.con.autocommit = True

    def rollback(self):
        if (self.transaction_level == 0):
            raise Error('Cannot rollback transaction, which was not started.')

        self.transaction_level -= 1
        if (self.transaction_level == 0):
            self.con.rollback()
            self.con.autocommit = True

    def executeonly(self, query, data = None):
            if data == None:
                return self.cur.execute(query)
            else:
                return self.cur.execute(query, data)

    def executemany(self, query, data):
                return self.cur.executemany(query, data)
